import time

import requests
import json

from datetime import datetime

def print_info(info):
    current_time = datetime.now()
    print(f'{current_time.strftime("%m-%d %H:%M:%S")}   {info}')


class Sigua:
    group_no = 'OYqigeRfz_FfnPic2C9_42_IM2ZNZTZq'
    app_id = 'jtUp9FOsd9'
    app_key = '96bb6789cee24649b9587341132d26ec'
    token = ''
    robot_no = '745501743278159'
    last_get_token_time = time.time()
    def get_token(self):
        # 请替换为实际的API URL ,token过期时间为7200秒
        url = f'https://api.siguatalk.com/robotapi/v1/token?app_id={self.app_id}&app_key={self.app_key}'

        # 请替换为实际的组ID和消息内容

        # 构建请求头
        headers = {
            'Content-Type': 'application/json',
        }

        response = requests.get(url, headers=headers)
        print('请求成功，响应内容:')
        print(response.text)
        token = response.json().get('token')
        self.token = token
        self.last_get_token_time = time.time()
        print(self.token)
        if token is None:
            err_code = response.json().get('err_code')

    def sendMessage(self,message_content):
        # 请替换为实际的API URL
        url = f'https://api.siguatalk.com/robotapi/v1/message/send?robot_no={self.robot_no}&token={self.token}'

        # 请替换为实际的组ID和消息内容


        # 构建请求头
        headers = {
            'Content-Type': 'application/json',
        }

        # 构建请求体
        payload = {
            "type": 'cmd',
            "session_open_id": self.group_no,
            "session_type": "2",
            "to_type": "2",
            "to": self.group_no,
            "content": {
                "cmd": "send-text",
                "params": json.dumps({"text": message_content})
            }
        }

        # 发送POST请求
        try:
            response = requests.post(url, json=payload, headers=headers)
            response.raise_for_status()  # 检查请求是否成功
            print('请求成功，响应内容:')
            print_info(response.text)
        except requests.exceptions.HTTPError as http_err:
            print(http_err)
        except Exception as err:
            print(err)


if __name__ == "__main__":

    sigua = Sigua()
    sigua.get_token()
    current_time = time.time()
    count = 0
    while True:
        count = count+1
        if current_time - sigua.last_get_token_time >7000:
            sigua.get_token()
        sigua.sendMessage(f"TestMassage : FC Juarez - Necaxa : Home -0.25 :{count}")
        time.sleep(60)